package com.abc.cloud.service.impl;

import com.abc.cloud.common.utils.Result;
import com.abc.cloud.dto.user.UserKeyCode;
import com.abc.cloud.dto.user.UserSpace;
import com.abc.cloud.dto.user.UserInfoAndRole;
import com.abc.cloud.entity.UserRoleRelationEntity;
import com.abc.cloud.service.UserRoleRelationService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.abc.cloud.common.utils.PageUtil;
import com.abc.cloud.common.utils.Query;

import com.abc.cloud.dao.UserDao;
import com.abc.cloud.entity.UserEntity;
import com.abc.cloud.service.UserService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

@Slf4j

@Service("userService")
public class UserServiceImpl extends ServiceImpl<UserDao, UserEntity> implements UserService {

    @Autowired
    public UserRoleRelationService userRoleRelationService;

    @Autowired UserService userService;
    @Override
    public PageUtil queryPage(Map<String, Object> params) {
        IPage<UserEntity> page = this.page(
                new Query<UserEntity>().getPage(params),
                new QueryWrapper<UserEntity>()
        );

        return new PageUtil(page);
    }

    @Override
    public UserSpace queryUserSpace(Long userId) {
        return this.baseMapper.queryUserSpace(userId);
    }

    @Override
    public UserEntity userLogin(UserEntity user) {
        return this.baseMapper.getByUsernameAndPassword(user);
    }

    @Override
    public UserEntity adminLogin(UserEntity user) {
        return this.baseMapper.getByUsernameAndPassword(user);
    }


//    获取用户info和身份
    @Override
    public UserInfoAndRole getUserInfoRole(Long userId){
        List<UserRoleRelationEntity> userRoleRelationEntityList = this.baseMapper.getRole(userId);
//        System.out.println("userRoleRelationEntityList = "  + userRoleRelationEntityList);
        List<Long> nums = new ArrayList<>();
        for(UserRoleRelationEntity u : userRoleRelationEntityList){
            nums.add(u.getRoleId());
        }

        UserEntity userInfo = this.baseMapper.getById(userId);
        UserInfoAndRole userInfoAndRole = new UserInfoAndRole();
        //将userInfo拷贝到user2,不拷贝password
        BeanUtils.copyProperties(userInfo, userInfoAndRole, "password");
        userInfoAndRole.setRole(nums);
        return userInfoAndRole;
    }


//      更新最后登录时间
        @Override
        public void setLastLoginTime(Long userId){
            UserEntity user = new UserEntity();
            user.setId(userId);
            user.setLastLoginTime(new Date());
            this.baseMapper.updateById(user);
        }
        //后台分页查询用户
        @Override
        public PageUtil getUserList(Map<String, Object> params) {
            Integer pageSize = Integer.parseInt((String)(params.get("pageSize")));   //一页展示多少条
            pageSize = pageSize > 0 ? pageSize : 1;
            Integer currPage = Integer.parseInt((String)params.get("currPage"));     //当前页数
            String searchContent = (String)params.get("searchContent");
            Integer totalCount = baseMapper.getCount(searchContent);        //总记录数
            Integer totalPage = totalCount / pageSize + (totalCount%pageSize > 0 ? 1 : 0);       //总页数
            List<UserEntity> userList = baseMapper.getUserList((currPage-1)*pageSize ,pageSize,searchContent);
            log.info("totalCount = {},pageSize = {},currPage = {},totalPage = {}", totalCount,pageSize,currPage,totalPage);
            for(UserEntity userEntity : userList){
                log.info("user = {}", userEntity);
            }
            PageUtil pageUtil = new PageUtil(userList,pageSize,currPage,totalCount,totalPage);
            return pageUtil;
//            return this.baseMapper.getUserList(searchContent);
        }
    //        管理员后台禁用用户账号
        @Override
        public void updateUserStatus(List<Long> userIds,Integer status) {
            baseMapper.updateUserStatus(userIds,status);
        }



    //        新增用户
        @Override
        @Transactional          //事务处理
        public String addUser(UserKeyCode user) {
            String username = user.getUsername();
            String password = user.getPassword();
            password = DigestUtils.md5DigestAsHex(password.getBytes());
            user.setPassword(password);
            log.info("MD5加密后的 user = {}", user);

            // 查找用户名
            LambdaQueryWrapper<UserEntity> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(UserEntity::getUsername,user.getUsername());
            UserEntity u = userService.getOne(queryWrapper);
            // 判断是否已经注册
            if(u==null){
                if(user.getNickname() == null)user.setNickname("iKun");
                user.setGender(1);
                user.setCreateTime(new Date());
                user.setUpdateTime(new Date());
                user.setTotalSpace(5*1024*1024L);
                user.setStatus(1);
                user.setAvatar("https://img0.baidu.com/it/u=4154833386,1880487480&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500");
                userService.save(user);
                //newUserId为新加入的user的id
                Long newUserId = user.getId();
                //为该新用户添加身份（用户）
                UserRoleRelationEntity userRoleRelation = new UserRoleRelationEntity();
                userRoleRelation.setUserId(newUserId);
                userRoleRelation.setRoleId(1L);//       1是用户
                userRoleRelationService.save(userRoleRelation);
                return null;
            }
            return "该用户名已存在";
        }


    //          修改用户已用内存
        @Transactional
        @Override
        public boolean saveFile(Long userId, Long fileSize) {
            UserSpace userSpace = baseMapper.getSpace(userId);
            if(fileSize > userSpace.getTotalSpace() - userSpace.getUseSpace()){
                return false;
            }
            UserEntity user = new UserEntity();
            user.setId(userId);
            user.setUseSpace(userSpace.getUseSpace() + fileSize);
            userService.updateById(user);
            return true;
        }

    @Override
    public UserSpace getSpace(Long userId) {
        return this.baseMapper.getSpace(userId);
    }
}